package com.summer.test.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.summer.core.annotations.ScopeType;
import com.summer.core.controller.EntityHome;
import com.summer.core.controller.LoginUserInfo;
import com.summer.core.util.FacesUtil;
import com.summer.test.model.SystemFee;
import com.summer.user.model.User;

@Component
@Scope(ScopeType.REQUEST)
public class SystemFeeHome extends EntityHome<SystemFee> {

	@Resource
	HibernateTemplate ht;
	@Resource
	LoginUserInfo loginUserInfo;

	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public String save() {

		try {
			System.out.println(getInstance().getName());
			String loginUserId = loginUserInfo.getLoginUserId();
			User user = getBaseService().get(User.class, loginUserId);

			if (getInstance().getId() == null
					|| getInstance().getId().equals("")) {
				
				List<String> list = ht.find(
						"select max(sf.id) from SystemFee sf ");
				Integer sfid = list.get(0) == null ?1:Integer.parseInt(list.get(0));
				getInstance().setId(sfid + 1 + "");
				getInstance().setOperUser(user);
				getInstance().setOperDatetime(new Date());
				getBaseService().save(getInstance());

				FacesUtil.addInfoMessage("保存成功！");

			} else {
				getInstance().setUpdateDatetime(new Date());
				getInstance().setUpdateUser(user);
				getBaseService().merge(getInstance());
				FacesUtil.addInfoMessage("修改成功！");
			}

			return FacesUtil.redirect("/admin/test/systemFee");
		} catch (DataAccessException e) {
			e.printStackTrace();
			FacesUtil.addErrorMessage("保存失败！");
		}
		return null;
	}

	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public String delete(String id) {

		SystemFee sf = ht.get(SystemFee.class, id);
		List list = ht.find(
				"select t from SystemLoanFee t where t.systemFee=?", sf);
		if (list.size() > 0) {
			FacesUtil.addErrorMessage("该记录下有其他子记录，不能删除");
			return null;
		}
		return super.delete(id);
	}

}
